﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;

namespace Jinndev {

    static class PublishMode {


        public static void Publish(string[] args) {
            Console.WriteLine("[Publish] " + string.Join(" ", args));

            string version = Util.FindArg(args, "-v", "-version");
            string description = Util.FindArg(args, "-d", "-description");

            if (string.IsNullOrWhiteSpace(version)) {
                Console.WriteLine("[Error] \"-version\" or \"-v\" not configured");
                return;
            }

            string rootDir = Directory.GetCurrentDirectory();

            PublishInfo publishInfo = new PublishInfo();
            publishInfo.version = version;
            publishInfo.description = description ?? version;
            publishInfo.publishTime = Util.GetTotalMs(DateTime.Now);
            publishInfo.entries = new List<FileEntry>();

            string[] files = Directory.GetFiles(rootDir, "*.*", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++) {
                string file = files[i];
                string filePath = file.Substring(rootDir.Length + 1);

                if (filePath == "PublishInfo.json" || filePath == "Updater.exe" || filePath == "Updater.dll" || filePath == "Updater.json" || filePath == "Updater.pdb") {
                    continue;
                }

                var entry = new FileEntry() {
                    path = filePath,
                    size = Util.GetFileSize(file),
                    md5 = Util.GetFileMD5(file)
                };
                publishInfo.entries.Add(entry);
                publishInfo.totalSize += entry.size;
            }

            var options = new JsonSerializerOptions();
            options.WriteIndented = true;

            string json = JsonSerializer.Serialize(publishInfo, options);
            File.WriteAllText("PublishInfo.json", json, Encoding.UTF8);
        }

    }

}
